package com.study.rabbitmq2.util;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author chenyeqing
 * @Date 2021/11/20 19:06
 */
public class ConnectionUtil {

    /**
     * 建立与RabbitMQ的连接
     * @return
     */
    public static Connection getConnection() {
        // 定义连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置服务地址
        factory.setHost("localhost");
        // 端口
        factory.setPort(5672);

        // 设置账号信息，用户名、密码、vhost
        // 设置虚拟机，一个MQ服务可以设置多个虚拟机，每个虚拟机就相当于一个独立的MQ
        factory.setVirtualHost("kavito");
        factory.setUsername("admin");
        factory.setPassword("123");

        Connection connection = null;
        try {
            // 通过工厂获取连接
            connection = factory.newConnection();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return connection;
    }
}
